package com.lv.suyiyong.hfr.fragment

import android.os.Bundle
import android.view.View
import android.widget.TextView
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.SPStaticUtils
import com.blankj.utilcode.util.SizeUtils
import com.lv.common.base.BaseFragment
import com.lv.common.imp.OnPositionTListener
import com.lv.common.network.model.DataResult
import com.lv.common.utils.ARoutUtils
import com.lv.common.utils.Constants
import com.lv.common.widget.recyclerview.decoration.SpacesItemDecoration
import com.lv.service.bean.CompanyTypeBean
import com.lv.service.bean.GoodsBean
import com.lv.service.bean.GoodsCategoryAttachedBean
import com.lv.service.bean.GoodsItemBean
import com.lv.service.model.ServiceViewModel
import com.lv.service.network.BaseYgxRsp
import com.lv.service.network.onBizError
import com.lv.service.network.onBizOK
import com.lv.service.network.onFailure
import com.lv.service.network.onSuccess
import com.lv.suyiyong.hfr.R
import com.lv.suyiyong.hfr.adapter.CompanyCategoryTabAdapter
import com.lv.suyiyong.hfr.databinding.FragmentCompanyCategoryLrBinding
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.withContext
import org.koin.androidx.viewmodel.ext.android.viewModel

/**
 * 作者： ygx
 * 创建日期：2023/3/10 3:49 PM
 * 签名： 天行健，君子以自强不息；地势坤，君子以厚德载物。
 * -    _              _           _     _   ____  _             _ _
 * -   / \   _ __   __| |_ __ ___ (_) __| | / ___|| |_ _   _  __| (_) ___
 * -  / _ \ | '_ \ / _` | '__/ _ \| |/ _` | \___ \| __| | | |/ _` | |/ _ \
 * - / ___ \| | | | (_| | | | (_) | | (_| |  ___) | |_| |_| | (_| | | (_) |
 * -/_/   \_\_| |_|\__,_|_|  \___/|_|\__,_| |____/ \__|\__,_|\__,_|_|\___/
 * <p>
 * You never know what you can do until you try !
 * ----------------------------------------------------------------
 * 描述： 公司分类 页面 自定义
 */
class CompanyCategoryLRFragment : BaseFragment(), View.OnClickListener {
    private var mCpyid: String = ""
    private var mFcaid: String = ""
    private var mCategoryFirst: String = ""
    private var mLeftPosition: Int = 0
    private var page: Int = 1
    private var pageSize: Int = Constants.pageSize
    private val parmasMap = mutableMapOf<String, String>()
    private var isLoading = true
    private var mLoadFooter: TextView? = null
    private val mBeans = mutableListOf<GoodsBean>()
    private val mLeftBeans = mutableListOf<GoodsCategoryAttachedBean>()
    private var mLeftAdapter: CompanyCategoryTabAdapter? = null
    private var mAdapter: CompanyCategoryRightParentAdapter? = null
    private val viewModel: ServiceViewModel by viewModel()
    private val mForshort = SPStaticUtils.getString(Constants.SP_KEY_ADDRESS_PROVINCE_FORSHORT)

    private val myScope: CoroutineScope = CoroutineScope(SupervisorJob())
    private var mBinding: FragmentCompanyCategoryLrBinding? = null

    override fun getLayoutRes() = R.layout.fragment_company_category_lr

    override fun bindView(view: View, savedInstanceState: Bundle?): ViewDataBinding {
        mBinding = FragmentCompanyCategoryLrBinding.bind(view).apply {
//            titleBar.setTitle("商品分类")
//            titleBar.onClickBackIcon {
//                activity?.finish()
//            }
//
//            llSearch.setOnClickListener(this@CompanyCategoryLRFragment)
//            ivShareBlack.setOnClickListener(this@CompanyCategoryLRFragment)
        }
        return mBinding!!
    }


    override fun onResume() {
        super.onResume()
//        if (mBeans.isEmpty() && mAdapter != null) {
//            mBinding?.refreshFragment?.autoRefresh()
//        }
    }


    override fun initConfig() {
        super.initConfig()
        initRecyclerView()

    }

    //    private var mProvince = ""
    override fun initData() {
        super.initData()

        arguments?.let {

            mCpyid = it.getString("cpyid", "")
        }
        parmasMap["cpyid"] = mCpyid
        parmasMap["code"] = "1"

        CompanyDetails()
//        lifecycleScope.launchWhenCreated {
//            val taskCompntyInfo = async { spuCategory() }.await()
//            initPage()
//
//        }
    }

    private fun initRecyclerView() {
        mLeftAdapter = CompanyCategoryTabAdapter(mLeftBeans)
        mBinding?.rvContentLeft?.adapter = mLeftAdapter

        mAdapter = CompanyCategoryRightParentAdapter(mBeans)
        mBinding?.rvContentRight?.adapter = mAdapter

        val footView = layoutInflater.inflate(
            R.layout.refresh_foot, null, false
        )
        mLoadFooter = footView.findViewById<TextView>(R.id.tv_load_dec)
        mAdapter?.addFooterView(footView)
        mBinding?.rvContentRight?.addItemDecoration(
            SpacesItemDecoration(0, SizeUtils.dp2px(10.0f), false)
        )
    }

    private fun CompanyDetails() {
        isLoading = true
        parmasMap["fcaid"] = mFcaid
        lifecycleScope.launchWhenCreated {
            val result: DataResult<BaseYgxRsp> =
                withContext(myScope.coroutineContext) {
                    viewModel.CompanyDetails(page, pageSize, parmasMap)
                }
            parseResult(result)
        }
    }

    private fun parseResult(data: DataResult<BaseYgxRsp>) {
        loadFinished()
        isLoading = false
        data.onSuccess {
            onBizOK<CompanyTypeBean> { code, data, message, result ->
                val attached = data?.attached
                if (mLeftBeans.isEmpty()) {
                    attached?.let { mLeftBeans.addAll(it) }
                    if (mLeftBeans.isNotEmpty()) {
                        mLeftPosition = 0
                        mLeftBeans[mLeftPosition].selected = true
//                        mFcaid = "${mLeftBeans[mLeftPosition].fcaid}"
                    }
                    mLeftAdapter?.notifyDataSetChanged()
                }
                val items = data?.items
                val list = items?.groupBy { it.fcaid }
                if (page == 1) {
                    mBeans.clear()
                    list?.forEach { (fcaid, listItems) ->
                        val name = listItems[0].fcname
                        mBeans.add(GoodsBean(0, fcaid ?: 0, 0, 0, listItems, name))
                    }
                } else {
                    if (mBeans.isNotEmpty()) {
                        val page1 = mBeans[mBeans.size - 1].page
                        val itemPre = mBeans[mBeans.size - 1].items
                        val listLast = mutableListOf<GoodsItemBean>()
                        itemPre?.let { listLast.addAll(it) }
                        list?.forEach { (fcaid, nextitems) ->
                            if (fcaid == page1) {
                                listLast.addAll(nextitems)
                                mBeans[mBeans.size - 1].items = listLast
                            } else {
                                val name = nextitems[0].fcname
                                mBeans.add(GoodsBean(0, fcaid ?: 0, 0, 0, nextitems, name))
                            }
                        }
                    }
                }
                mAdapter?.notifyDataSetChanged()

//                MyUtils.recyclerviewSetData(
//                    page, pageSize, mBinding?.refreshFragment, mBeans, items, mAdapter
//                )
                initEmptyView()
                mBinding?.refreshFragment?.finishRefresh()
                mBinding?.refreshFragment?.finishLoadMore()
                if ((items?.size ?: 0) < pageSize) {
                    mBinding?.refreshFragment?.setEnableLoadMore(false)
                    mLoadFooter?.text = "暂无更多数据"
                } else {
                    mLoadFooter?.text = "上滑查看更多分类"
                    mBinding?.refreshFragment?.setEnableLoadMore(true)
                }
            }
            onBizError<GoodsBean> { code, message, data ->
                mBinding?.refreshFragment?.finishRefresh()
                mBinding?.refreshFragment?.finishLoadMore()
                initEmptyView()
            }
        }
        data.onFailure {
            mBinding?.refreshFragment?.finishRefresh()
            mBinding?.refreshFragment?.finishLoadMore()
            initEmptyView()
        }
    }

    private fun initEmptyView() {
        if (mBeans.isEmpty()) {
            mAdapter?.setEmptyView(getEmptyView(mBinding?.rvContentRight!!))
        }
    }


    override fun initEvents() {
        super.initEvents()
        mBinding?.refreshFragment?.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onRefresh(refreshLayout: RefreshLayout) {
//                mBinding?.rvContentRight?.scrollToPosition(0)
                page = 1
                mBeans.clear()
                mAdapter?.notifyDataSetChanged()
                if (mLeftBeans.isNotEmpty()) {
//                    mFcaid = "${mLeftBeans[mLeftPosition].fcaid}"
                    mCategoryFirst = mLeftBeans[mLeftPosition].name ?: ""
                } else {
                    mFcaid = ""
                    mCategoryFirst = ""
                }
                CompanyDetails()
            }

            override fun onLoadMore(refreshLayout: RefreshLayout) {
                page++
                CompanyDetails()
            }
        })
        mLeftAdapter?.onViewClickListener = OnPositionTListener { position, data ->
            if (mLeftPosition == position || isLoading) {
                return@OnPositionTListener
            }
            mLeftBeans[mLeftPosition].selected = false
            mLeftAdapter?.notifyItemChanged(mLeftPosition, R.id.tv_name)
            mLeftPosition = position
            mLeftBeans[mLeftPosition].selected = true
            mLeftAdapter?.notifyItemChanged(mLeftPosition, R.id.tv_name)
            mFcaid = "${mLeftBeans[mLeftPosition].fcaid}"
//            mType = mLeftBeans[mLeftPosition].type ?: "0"
            mBinding?.refreshFragment?.autoRefresh()
        }
        mAdapter?.onViewItemClickListener = OnPositionTListener { position, data ->
            ARouter.getInstance().build(ARoutUtils.GoodsDetilsActivity).withString("spuid", data.id)
                .navigation()
        }
//        mAdapter?.onViewTitleClickListener = OnPositionTListener { position, data ->
//            ARouter.getInstance()
//                .build(ARoutUtils.CompanyCategoryTabSearchActivity)
//                .withParcelable("companyInfo", mCompanyInfo)
//                .withString("search", data.secname)
//                .withString("fcaid", "${data.fcaid}")
//                .withString("searchId", "${data.secaid}")
//                .navigation()
//        }
        val layoutManager = mBinding?.rvContentRight?.layoutManager as LinearLayoutManager
        mBinding?.rvContentRight?.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
            }

            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                val lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition()
                if (lastVisibleItemPosition != RecyclerView.NO_POSITION) {
                    // 获取到了有效位置，可以使用这个位置来获取对应的条目数据
                    var lastVisibleItem: GoodsBean? = null
                    try {
                        lastVisibleItem = mAdapter?.getItem(lastVisibleItemPosition)

                        val position =
                            mLeftBeans.indexOfFirst { item -> item.fcaid == lastVisibleItem?.page }
                        if (position >= 0 && mLeftPosition != position) {
//                            if (position != mLeftPosition) {
                            mLeftBeans[mLeftPosition].selected = false
                            mLeftAdapter?.notifyItemChanged(mLeftPosition, R.id.tv_name)
                            mLeftBeans[position].selected = true
                            mLeftPosition = position
                            mLeftAdapter?.notifyItemChanged(mLeftPosition, R.id.tv_name)
//                            mFcaid = "${mLeftBeans[mLeftPosition].fcaid}"
                        }
                    } catch (e: Exception) {
                        if (lastVisibleItem == null && lastVisibleItemPosition == mLeftBeans.size) {
                            val position = mLeftBeans.size - 1
                            if (!mLeftBeans[position].selected) {
                                mLeftBeans[mLeftPosition].selected = false
                                mLeftAdapter?.notifyItemChanged(mLeftPosition, R.id.tv_name)
                                mLeftPosition = mLeftBeans.size - 1
                                mLeftBeans[mLeftPosition].selected = true
                                mLeftAdapter?.notifyItemChanged(mLeftPosition, R.id.tv_name)
                            }
                        }
                    }
                }
            }
        })
    }


    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.ll_search -> {
//                ARouter.getInstance()
//                    .build(ARoutUtils.CompanyCategoryTabSearchActivity)
//                    .withParcelable("companyInfo", mCompanyInfo)
//                    .navigation()
            }

            R.id.iv_share_black -> {
//                YgxManager.showDialogShare(
//                    requireActivity(),
//                    mCompanyInfo?.name ?: "",
//                    mCompanyInfo?.caption ?: "这个用户很懒，什么都没有留下~",
//                    "${Constants.KEY_SHARE_HEADER_SYY}${Constants.KEY_SHARE_COMPANY}${mCompanyInfo?.id}${Constants.KEY_SHARE_COMPANY_PRO}$mForshort",
//                    Constants.KEY_SHARE_COMPANY_CASH_WEIXIN + mCompanyInfo?.id + "_" + mForshort + Constants.KEY_SHARE_COMPANY_CASH_WEIXIN_END,
//                    mCompanyInfo?.logo ?: "", -1, OnPositionListener {
//                        LiveEventBus.get(CompanyShareEvent::class.java).post(CompanyShareEvent())
//                    }
//                )
            }
        }
    }

    companion object {
        fun newInstance(cpyid: String): CompanyCategoryLRFragment {
            val args = Bundle()
            args.putString("cpyid", cpyid)
            val fragment = CompanyCategoryLRFragment()
            fragment.arguments = args
            return fragment
        }
    }
}